package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.SysRoleMenu;
import com.hzhc.mapper.SysRoleMenuMapper;
import com.hzhc.service.SysRoleMenuService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.SysRoleVo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色与菜单对应关系 服务实现类
 * </p>
 *
 * @author 功不唐捐
 * @since 2024-04-07
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {
    @Override
    public ResultUtil<T> updateRoleMenu(SysRoleVo vo) {
        //新菜单角色为空,删除所有角色菜单
        if (vo.getMenuList().isEmpty()) {
            boolean b = remove(Wrappers.<SysRoleMenu>lambdaUpdate()
                    .eq(SysRoleMenu::getRoleId, vo.getId()));
            return ResultUtil.ok();
        }
        //原角色菜单为空,添加;不为空,添加新菜单,移除菜单集合外数据
        List<Long> oldMenus = baseMapper.selectRoleMenuList(vo.getId());
        if (oldMenus == null || oldMenus.isEmpty()) {
            List<SysRoleMenu> newMenus = handle(vo.getMenuList(), vo);
            boolean b = saveBatch(newMenus);
            return b ? ResultUtil.ok() : ResultUtil.fail();
        }
        //原角色菜单不为空
        List<Long> news = vo.getMenuList().stream().filter(s -> !oldMenus.contains(s)).collect(Collectors.toList());
        List<SysRoleMenu> newList = handle(news, vo);
        if (!newList.isEmpty()) {
            saveBatch(newList);
        }
        boolean b = remove(Wrappers.<SysRoleMenu>lambdaUpdate()
                .eq(SysRoleMenu::getRoleId, vo.getId())
                .notIn(SysRoleMenu::getMenuId, vo.getMenuList()));
        return ResultUtil.ok();
    }

    @Override
    public List<Long> getRoleMenuList(SysRoleVo vo) {
        return baseMapper.selectRoleMenuList(vo.getId());
    }

    private List<SysRoleMenu> handle(List<Long> newIds, SysRoleVo vo) {
        List<SysRoleMenu> newMenus = new ArrayList<>();
        SysRoleMenu menu;
        //原角色菜单为空
        for (Long l : newIds) {
            menu = new SysRoleMenu();
            menu.setRoleId(vo.getId())
                    .setMenuId(l);
            newMenus.add(menu);
        }
        return newMenus;
    }
}
